package io.youngledo.usb;

import io.youngledo.usb.connection.StorageConnection;
import io.youngledo.usb.storage.StorageObject;
import io.youngledo.usb.util.FileUtils;
// import io.youngledo.usb.util.FileIconManager;  // 暂时注释，之后添加
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.*;

import java.time.format.DateTimeFormatter;

/// 连接标签页，包含每个连接的独立UI组件
///
public class ConnectionTab extends VBox {

    private final StorageConnection connection;
    private final UniversalStorageBrowser mainApp;

    // UI组件
    private ComboBox<String> bucketComboBox;
    private ObservableList<String> availableBuckets;
    private Label pathLabel;
    private TextField searchField;
    private TableView<StorageObject> fileTableView;
    private ObservableList<StorageObject> allFiles;
    private ObservableList<StorageObject> filteredFiles;
    private ProgressIndicator loadingIndicator;
    private Label loadingLabel;
    private StackPane contentPane;
    private VBox loadingBox;

    // 文件操作按钮
    private Button backButton;
    private Button uploadButton;
    private Button downloadButton;
    private Button deleteButton;
    private Button newFolderButton;
    private Button refreshButton;

    // 当前状态
    private String currentBucket;

    public ConnectionTab(StorageConnection connection, UniversalStorageBrowser mainApp) {
        this.connection = connection;
        this.mainApp = mainApp;

        // 初始化数据
        availableBuckets = FXCollections.observableArrayList();
        allFiles = FXCollections.observableArrayList();
        filteredFiles = FXCollections.observableArrayList();

        // 创建UI
        initializeUI();

        // 设置样式
        setSpacing(0);
        setPadding(new Insets(0));
    }

    private void initializeUI() {
        // 导航栏
        HBox navigationBar = createNavigationBar();

        // 文件表格 (先创建，因为工具栏创建时需要引用)
        fileTableView = createFileTableView();

        // 创建加载指示器
        loadingIndicator = new ProgressIndicator();
        loadingIndicator.setPrefSize(60, 60);
        loadingLabel = new Label("正在加载文件列表...");
        loadingLabel.getStyleClass().add("loading-label");

        loadingBox = new VBox(10);
        loadingBox.setAlignment(Pos.CENTER);
        loadingBox.getChildren().addAll(loadingIndicator, loadingLabel);
        loadingBox.getStyleClass().add("loading-box");

        // 使用 StackPane 叠加表格和加载指示器
        contentPane = new StackPane();
        contentPane.getChildren().addAll(fileTableView, loadingBox);

        // 初始隐藏加载指示器
        loadingBox.setVisible(false);

        // 文件操作工具栏
        ToolBar fileOperationToolBar = createFileOperationToolBar();

        getChildren().addAll(navigationBar, fileOperationToolBar, contentPane);
        VBox.setVgrow(contentPane, Priority.ALWAYS);
    }

    private HBox createNavigationBar() {
        HBox navigationBar = new HBox();
        navigationBar.setSpacing(10);
        navigationBar.setPadding(new Insets(8, 10, 8, 10));
        navigationBar.setAlignment(Pos.CENTER_LEFT);
        navigationBar.getStyleClass().add("navigation-bar");

        // 存储桶选择下拉框
        bucketComboBox = new ComboBox<>(availableBuckets);
        bucketComboBox.setPromptText("请选择存储桶");
        bucketComboBox.setPrefWidth(200);
        bucketComboBox.setPrefHeight(32);

        // 存储桶选择事件
        bucketComboBox.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal != null) {
                currentBucket = newVal;
                connection.setCurrentBucket(currentBucket);
                connection.setCurrentPrefix("");
                mainApp.loadBucketFilesForTab(this);
                updatePathLabel();
                updateBackButton();
                updateFileOperationButtonStates();
            } else {
                currentBucket = null;
                allFiles.clear();
                filteredFiles.clear();
                updatePathLabel();
                updateBackButton();
                updateFileOperationButtonStates();
            }
        });

        // 路径显示
        pathLabel = new Label("Path: /");
        pathLabel.getStyleClass().add("path-label");
        pathLabel.setPrefHeight(32);
        pathLabel.setAlignment(Pos.CENTER_LEFT);

        // 搜索框
        searchField = new TextField();
        searchField.setPromptText("搜索文件...");
        searchField.setPrefWidth(200);
        searchField.setPrefHeight(32);
        searchField.textProperty().addListener((obs, oldVal, newVal) -> filterFiles(newVal));

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        // 刷新存储桶按钮
        Button refreshBucketButton = new Button("刷新");
        refreshBucketButton.setTooltip(new Tooltip("刷新存储桶"));
        refreshBucketButton.setMinWidth(60);
        refreshBucketButton.setOnAction(e -> refreshBucketList());

        navigationBar.getChildren().addAll(bucketComboBox, refreshBucketButton, pathLabel, spacer, searchField);
        return navigationBar;
    }

    /// 刷新存储桶列表
    ///
    private void refreshBucketList() {
        mainApp.refreshBucketsForTab(this);
    }

    private ToolBar createFileOperationToolBar() {
        // 创建按钮
        backButton = new Button("↑ 返回");
        uploadButton = new Button("上传");
        downloadButton = new Button("下载");
        deleteButton = new Button("删除");
        newFolderButton = new Button("新建文件夹");
        refreshButton = new Button("刷新");

        // 配置按钮 - 根据文字长度调整宽度
        configureButton(backButton, "返回上级目录", this::navigateBack, 100);
        configureButton(uploadButton, "上传文件到当前存储桶", () -> mainApp.handleUploadForTab(this), 80);
        configureButton(downloadButton, "下载选中的文件", () -> mainApp.handleDownloadForTab(this), 80);
        configureButton(deleteButton, "删除选中的文件或文件夹", () -> mainApp.handleDeleteForTab(this), 80);
        configureButton(newFolderButton, "在当前位置创建新文件夹", () -> mainApp.handleNewFolderForTab(this), 120);
        configureButton(refreshButton, "刷新当前文件列表", () -> mainApp.handleRefreshForTab(this), 80);

        // 初始状态
        backButton.setDisable(true);
        updateFileOperationButtonStates();

        ToolBar toolBar = new ToolBar(backButton, new Separator(), uploadButton, downloadButton,
                                     new Separator(), deleteButton, newFolderButton, new Separator(), refreshButton);
        toolBar.setPadding(new Insets(5, 10, 5, 10));
        toolBar.getStyleClass().add("toolbar");

        return toolBar;
    }

    private void configureButton(Button button, String tooltipText, Runnable action, int minWidth) {
        // 高度由CSS统一控制，设置最小宽度让按钮可以自适应
        button.setMinWidth(minWidth);

        if (tooltipText != null) {
            button.setTooltip(new Tooltip(tooltipText));
        }

        if (action != null) {
            button.setOnAction(e -> action.run());
        }
    }

    private TableView<StorageObject> createFileTableView() {
        TableView<StorageObject> tableView = new TableView<>();

        // 创建表格列
        TableColumn<StorageObject, String> nameColumn = new TableColumn<>("名称");
        TableColumn<StorageObject, String> sizeColumn = new TableColumn<>("大小");
        TableColumn<StorageObject, String> typeColumn = new TableColumn<>("类型");
        TableColumn<StorageObject, String> lastModifiedColumn = new TableColumn<>("修改时间");

        // 设置列宽
        nameColumn.setPrefWidth(250);
        sizeColumn.setPrefWidth(100);
        typeColumn.setPrefWidth(100);
        lastModifiedColumn.setPrefWidth(200);

        // 设置列数据绑定
        nameColumn.setCellValueFactory(cellData ->
            new javafx.beans.property.SimpleStringProperty(cellData.getValue().name()));

        // 为名称列设置图标
        nameColumn.setCellFactory(column -> new TableCell<StorageObject, String>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    StorageObject object = getTableView().getItems().get(getIndex());
                    String icon = object.isDirectory() ? "📁" : "📄"; // 临时简单图标
                    setText(icon + " " + item);
                }
            }
        });

        sizeColumn.setCellValueFactory(cellData -> {
            StorageObject obj = cellData.getValue();
            if (obj.isDirectory()) {
                return new javafx.beans.property.SimpleStringProperty("--");
            } else {
                return new javafx.beans.property.SimpleStringProperty(FileUtils.formatSize(obj.size()));
            }
        });

        typeColumn.setCellValueFactory(cellData ->
            new javafx.beans.property.SimpleStringProperty(
                cellData.getValue().isDirectory() ? "文件夹" : "文件"
            ));

        lastModifiedColumn.setCellValueFactory(cellData ->
            new javafx.beans.property.SimpleStringProperty(formatDate(cellData.getValue().lastModified())));

        tableView.getColumns().addAll(nameColumn, sizeColumn, typeColumn, lastModifiedColumn);

        // 根据许可证设置选择模式
        // 专业版：支持多选；社区版：仅单选
        if (io.youngledo.usb.license.FeatureGate.isEnabled(io.youngledo.usb.license.Feature.BATCH_OPERATIONS)) {
            tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        } else {
            tableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        }

        tableView.setItems(filteredFiles);

        // 添加选择监听器来更新按钮状态
        tableView.getSelectionModel().getSelectedItems().addListener(
            (javafx.collections.ListChangeListener<StorageObject>) change -> updateFileOperationButtonStates());

        // 添加双击事件处理（用于进入文件夹）
        tableView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                StorageObject selectedObject = tableView.getSelectionModel().getSelectedItem();
                if (selectedObject != null && selectedObject.isDirectory()) {
                    enterFolder(selectedObject);
                }
            }
        });

        return tableView;
    }

    // Getters
    public StorageConnection getConnection() {
        return connection;
    }

    public String getCurrentBucket() {
        return currentBucket;
    }

    public ComboBox<String> getBucketComboBox() {
        return bucketComboBox;
    }

    public ObservableList<String> getAvailableBuckets() {
        return availableBuckets;
    }

    public TableView<StorageObject> getFileTableView() {
        return fileTableView;
    }

    public ObservableList<StorageObject> getAllFiles() {
        return allFiles;
    }

    public ObservableList<StorageObject> getFilteredFiles() {
        return filteredFiles;
    }

    // 业务方法
    public void updatePathLabel() {
        if (currentBucket == null) {
            pathLabel.setText("Path: /");
        } else {
            String prefix = connection.getCurrentPrefix();
            String path = "/" + currentBucket + "/" + (prefix != null ? prefix : "");
            pathLabel.setText("Path: " + path);
        }
    }

    public void updateBackButton() {
        if (currentBucket == null) {
            backButton.setDisable(true);
            return;
        }

        String currentPrefix = connection.getCurrentPrefix();
        backButton.setDisable(currentPrefix == null || currentPrefix.isEmpty());
    }

    public void updateFileOperationButtonStates() {
        boolean hasBucket = currentBucket != null;
        boolean hasSelectedFiles = !fileTableView.getSelectionModel().getSelectedItems().isEmpty();

        uploadButton.setDisable(!hasBucket);
        newFolderButton.setDisable(!hasBucket);
        downloadButton.setDisable(!hasBucket || !hasSelectedFiles);
        deleteButton.setDisable(!hasBucket || !hasSelectedFiles);
        refreshButton.setDisable(!hasBucket);
    }

    private void filterFiles(String searchText) {
        if (searchText == null || searchText.trim().isEmpty()) {
            filteredFiles.setAll(allFiles);
        } else {
            String lowerCaseFilter = searchText.toLowerCase();
            filteredFiles.setAll(
                allFiles.stream()
                    .filter(file -> file.name().toLowerCase().contains(lowerCaseFilter))
                    .toList()
            );
        }
    }

    private void navigateBack() {
        mainApp.navigateBackForTab(this);
    }

    private void enterFolder(StorageObject folder) {
        if (!folder.isDirectory()) return;

        // 更新当前路径前缀
        String newPrefix = folder.key();
        if (!newPrefix.endsWith("/")) {
            newPrefix += "/";
        }

        connection.setCurrentPrefix(newPrefix);

        // 重新加载文件列表
        mainApp.loadBucketFilesForTab(this);

        // 更新UI状态
        updatePathLabel();
        updateBackButton();
    }

    private String formatDate(java.time.LocalDateTime dateTime) {
        if (dateTime == null) return "";
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /// 显示加载指示器
    ///
    public void showLoading() {
        javafx.application.Platform.runLater(() -> {
            loadingBox.setVisible(true);
        });
    }

    /// 隐藏加载指示器
    ///
    public void hideLoading() {
        javafx.application.Platform.runLater(() -> {
            loadingBox.setVisible(false);
        });
    }
}